#include "stdlib.h"
#include "string.h"
#include "nid.h"
//#include "common.h"
//#include "utils.h"
#include "constants.h"
#include "md5.h"

int genUniqueString(char* in, char** out)
{

	int exit_code=0, i;
	//char _out[RESULT_LENGTH+CHARACTERS_TO_SKIP+1];
	char* _out = (char*)malloc(sizeof(char)*(RESULT_LENGTH+CHARACTERS_TO_SKIP+1));
    	
    	MD5_CTX mdContext;
    	char sum[HASH_LENGTH];

	MD5Init (&mdContext);
    	MD5Update (&mdContext, in, strlen(in));

	memset(_out, ' ', RESULT_LENGTH);

	MD5Final (&mdContext);

	for(i = 0; i < 16; i++)
	    sum[i]=mdContext.digest[i];

	if((exit_code = encode(HASH_LENGTH, sum, (unsigned)(RESULT_LENGTH+CHARACTERS_TO_SKIP), _out))){
		return exit_code;
	}

	_out[RESULT_LENGTH+CHARACTERS_TO_SKIP]='\0';
	_out[RESULT_LENGTH+CHARACTERS_TO_SKIP-2]='\0'; /* do not show last 2 '==' */

	//printf("%s\n", in); printf("%s\n", _out);

	*out = _out;

	return 0;
}

void freeUniqueString(char* s)
{
	if(s!=NULL){
		free(s);
	}
}
